﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Icms.Core.Model;
using Icms.Core.Service;
using Icms.WebUI.Builder;
using Icms.WebUI.Dto;
using Omu.Awesome.Mvc;

namespace Icms.WebUI.Controllers
{
    [Authorize(Roles="admin")]
    public class UserController : Crudere<User, UserCreateInput, UserInput>
    {
        private new readonly IUserService s;

        public UserController(IUserService s, IMapper<User, UserCreateInput> v, IMapper<User, UserInput> ve): base(s, v, ve)
        {
            this.s = s;
        }

        public virtual ActionResult Search(string search, int page = 1, int ps = 5)
        {
            var src = s.Where(o => o.LastName.StartsWith(search) || o.FirstName.StartsWith(search));
            var rows = this.RenderView("rows", src.OrderBy(u => u.Id).Skip((page - 1) * ps).Take(ps));

            return Json(new { rows, more = src.Count() > page * ps });
        }

        public ActionResult ChangePassword(Guid userId)
        {
            return View(new ChangePasswordInput { UserId = userId });
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordInput input)
        {
            if (!ModelState.IsValid) return View(input);
            s.ChangePassword(input.UserId, input.Password);
            return Content("ok");
        }

        protected override UserCreateInput BeforeCreate(UserCreateInput o)
        {
            o.FirstName = "-";
            o.LastName = "-";
            o.Roles = new List<Guid> { new Guid("f68ff443-2b4a-e011-8dfb-000c296c2a7a") };
            return o;
        }
    }
}